import requests  
import base64  
import json  
import time  
class insightFace():
    #获取ak,sk
    def access_tokens(self):
        ak = 'your_ak'
        sk = 'your_sk'
        
        # client_id 为官网获取的AK， client_secret 为官网获取的SK
        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(ak,sk)
        response = requests.get(host)
        if response:
            return response.json()['access_token']

    def imgdata(self,file1path,name=None,user_list=None):
        f = open(r'%s' % file1path, 'rb')
        pic = base64.b64encode(f.read())
        f.close()
        
        # 人脸搜索params
        if name =='face_search':
            params = json.dumps({"image": str(pic, 'utf-8'), 
                             "image_type": "BASE64", "group_id_list": "test","quality_control":"LOW","liveness_control":"NORMAL"})        
        # 人脸注册params
        elif name == 'face_registration':
            params = json.dumps({"image": str(pic, 'utf-8'), "image_type": "BASE64", 
                     "group_id": "test","user_id":user_list[0],"user_info":user_list[1],
                     "quality_control":"LOW","liveness_control":"NORMAL"})
        # 人脸质量检测params
        else:
            params = json.dumps({"image": str(pic, 'utf-8'), "image_type": "BASE64", "face_type": "LIVE", "quality_control": "LOW"})
        return params
    """
        调用人脸注册API
    """
    #可以用
    def face_registration(self,file1path,user):
        access_token = self.access_tokens()
        params = self.imgdata(file1path,'face_registration',user)
        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add"
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/json'}
        response = requests.post(request_url, data=params, headers=headers).json()
        if response['error_msg']=='SUCCESS':
            self.registration = True
            print("注册成功")
            self.reg_msg = "注册成功"
            self.on = False
        elif response['error_msg']=='face already exist':
            print('您已经注册过了！')
            self.registration = True
            self.reg_msg = '您已经注册过了！'
            self.on = False
        else:
            self.reg_msg = '您已经注册过了！'
            self.on = False
    #人脸质量检测
    #可以用
    def picture_quality(self,file1path):
        access_token = self.access_tokens()
        assert access_token != None,'access_token is None'
        params = self.imgdata(file1path)
        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/json'}
        response = requests.post(request_url, data=params, headers=headers).json()
        print(response)
        if response['error_msg'] == 'SUCCESS':
            score = response['result']['face_list'][0]['face_probability']
            print("得分",score,type(score))
            if (type(score) == float) | (type(score) == int):
                if score>=0.8:
                    recognize = False
                    return True
                else:
                    recognize = True
                    print(score)
                    return False
            
            else:
                recognize = True
                print(response['error_msg'])
                return False
        elif response['error_msg']=='match user is not found':
            return False
            print('请您先进行注册!')
    """
        调用人脸搜索API
    """
    #可以用
    def face_search(self,file1path):
        access_token = self.access_tokens()
        assert access_token != None,'access_token is None'
        params = self.imgdata(file1path,'face_search')
        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/search"
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/json'}
        response = requests.post(request_url, data=params, headers=headers).json()
        if response['error_msg']=='SUCCESS':
            #user_id = response['result']['user_list'][0]['user_id']
            #times = time.time()
            #this_time = time.localtime(times)
            #punch_time = "{}-{}-{} {}:{}:{}".format(this_time.tm_year,this_time.tm_mon,this_time.tm_mday,this_time.tm_hour,this_time.tm_min,this_time.tm_sec)
            print("找到了")
            return True
        elif response['error_msg']=='match user is not found':
            self.search_msg = '请您先进行注册!'
            print('请您先进行注册!')
            return False
        else:
            self.search_msg = response['error_msg']
            return 'error_msg' 
    #人脸删除
    def face_getlist(self,user_id):
        '''
        获取用户人脸列表并删除
        '''
        access_token = self.access_tokens()
        assert access_token != None,'access_token is None'
        # 人脸删除
        def face_delete(user_idx,face_token):
            request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/delete"

            params = json.dumps({ "user_id": user_idx, "group_id": "test","face_token":face_token})
            request_url = request_url + "?access_token=" + access_token
            headers = {'content-type': 'application/json'}
            response = requests.post(request_url, data=params, headers=headers).json()
            if response['error_code']!=0:
                del_msg = response['error_msg']
            else:
                del_msg = "删除成功"
            print(del_msg)            
        # 获取用户的face_token  
        request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/getlist"
        params = json.dumps({ "user_id": user_id, "group_id": "test"})
        request_url = request_url + "?access_token=" + access_token
        headers = {'content-type': 'application/json'}
        response = requests.post(request_url, data=params, headers=headers).json()
        if response['error_msg']=='SUCCESS':
            for i in response['result']['face_list']:
                face_token = i['face_token']
                face_delete(user_id,face_token)
        else:
            print(response['error_msg'])
'''
if __name__ == '__main__':
    a=insightFace()
    a.face_registration('./1.jpg','name')
    a.face_search('./1.jpg')
    a.picture_quality('./OIP-C.jpeg')
'''
